package ace.module.captcha.sms.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.core.exception.BusinessException;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.AbstractSpringDtoManager;
import ace.cmp.i18n.api.MessageSourceAssertService;
import ace.module.captcha.sms.api.constant.CaptchaSmsErrorCodeConstant;
import ace.module.captcha.sms.api.enums.CaptchaSmsApplicationStatusEnum;
import ace.module.captcha.sms.api.model.dto.CaptchaSmsApplicationDto;
import ace.module.captcha.sms.core.impl.dao.entity.CaptchaSmsApplication;
import ace.module.captcha.sms.core.impl.manager.CaptchaSmsApplicationManager;
import ace.module.captcha.sms.core.impl.manager.cache.CaptchaSmsApplicationCacheDbManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 短信验证码应用 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class CaptchaSmsApplicationManagerImpl
    extends AbstractSpringDtoManager<CaptchaSmsApplication, Long, CaptchaSmsApplicationDto>
    implements CaptchaSmsApplicationManager {

  private final MessageSourceAssertService assertService;
  private final CaptchaSmsApplicationCacheDbManager captchaSmsApplicationCacheDbManager;

  @Override
  public CaptchaSmsApplication getAndCheckAllById(Long id) {
    CaptchaSmsApplication captchaSmsApplication =
        this.captchaSmsApplicationCacheDbManager.getById(id);

    this.checkAll(captchaSmsApplication);

    return captchaSmsApplication;
  }

  @Override
  public CaptchaSmsApplication getAndCheckAllByKey(String key) {
    CaptchaSmsApplication captchaSmsApplication =
        this.captchaSmsApplicationCacheDbManager.getByKey(key);

    this.checkAll(captchaSmsApplication);

    return captchaSmsApplication;
  }

  private void checkAll(CaptchaSmsApplication captchaSmsApplication) {
    assertService.isNull(
        captchaSmsApplication,
        CaptchaSmsApplication.class.getName() + ".not-exist",
        new Object[]{},
        "短信验证应用-数据不存在",
        msg -> {
          throw new BusinessException(CaptchaSmsErrorCodeConstant.CAPTCHA_SMS_VERITY_CODE_NO_CONFIG, msg);
        });

    assertService.isFalse(
        CaptchaSmsApplicationStatusEnum.NORMAL.getCode().equals(captchaSmsApplication.getStatus()),
        CaptchaSmsApplication.class.getName() + ".is-locked",
        new Object[]{},
        "短信验证应用-已锁定",
        msg -> {
          throw new BusinessException(CaptchaSmsErrorCodeConstant.CAPTCHA_SMS_VERITY_CODE_NO_CONFIG, msg);
        });

    assertService.isFalse(
        CoreConstant.DELETE_FLAG_NOT.equals(captchaSmsApplication.getDeleteFlag()),
        CaptchaSmsApplication.class.getName() + ".is-deleted",
        new Object[]{},
        "短信验证应用-数据不存在",
        msg -> {
          throw new BusinessException(CaptchaSmsErrorCodeConstant.CAPTCHA_SMS_VERITY_CODE_NO_CONFIG, msg);
        });
  }
}
